"""
欢迎策略处理器
"""
import os
import random
import time
import uuid
from typing import List, Dict, Any, Optional
from datetime import datetime

from app.utils.logger import Logger
from app.services.service_locator import ServiceLocator
from app.services.config_service import IConfigService
from app.services.audio_service import IAudioService
from app.models.audio_item import AudioItem
from app.services.main_speech_manager import MainSpeechManager
from app.utils.username_processor import process_username  # 导入用户名处理函数


class WelcomeStrategyHandler:
    """欢迎策略处理器"""
    
    def __init__(self, config_path):
        self.config_path = config_path
        self.welcome_speech_dir = os.path.join(config_path, "话术管理", "欢迎话术")
        self.logger = Logger.get_logger("welcome_strategy_handler")
        
        # 获取话术管理器
        self.speech_manager = MainSpeechManager(config_path)
        
        # 流量等级对应的文件名
        self.flow_level_files = {
            "low": "低速.txt",
            "medium": "中速.txt",
            "high": "高速.txt"
        }
        
        # 初始化话术缓存
        self._speeches = {}
        
        # 加载欢迎话术
        self._load_welcome_speeches()
    
    def handle_users(self, users: List[str], flow_level: str) -> int:
        """
        根据流量等级处理用户欢迎
        
        @param users: 用户列表
        @param flow_level: 流量等级
        @return: 实际处理的用户数
        """
        if not users:
            self.logger.debug("用户列表为空，跳过处理")
            return 0
            
        self.logger.info(f"处理用户欢迎，流量等级: {flow_level}, 用户数: {len(users)}")
        self.logger.debug(f"待处理用户列表: {users}")
            
        if flow_level == "high":
            # 高流量：仅记录日志
            self.logger.info(f"高流量期间，跳过欢迎 {len(users)} 个用户")
            return 0
            
        elif flow_level == "medium":
            # 中流量：随机欢迎部分用户
            # 获取配置服务
            config_service = ServiceLocator.get(IConfigService)
            if not config_service:
                self.logger.error("无法获取配置服务，跳过处理")
                return 0
                
            # 获取触发比例作为随机比例
            random_ratio = config_service.get("flow_welcome", {}).get("trigger_ratio", 0.5)
            
            # 计算要选择的用户数
            select_count = max(1, int(len(users) * random_ratio))
            
            self.logger.info(f"中流量策略，随机比例: {random_ratio:.2f}, 将选择 {select_count}/{len(users)} 个用户")
            
            # 随机选择用户
            random.shuffle(users)
            selected_users = users[:select_count]
            
            self.logger.debug(f"已随机选择用户: {selected_users}")
            
            # 处理选中的用户
            self._process_users(selected_users, flow_level)
            return len(selected_users)
            
        else:  # low
            # 低流量：欢迎所有用户
            self.logger.info(f"低流量策略，欢迎所有 {len(users)} 个用户")
            self._process_users(users, flow_level)
            return len(users)
    
    def _process_users(self, users: List[str], flow_level: str):
        """
        处理用户欢迎
        
        @param users: 用户列表
        @param flow_level: 流量等级
        """
        # 获取音频服务
        audio_service = ServiceLocator.get(IAudioService)
        if not audio_service:
            self.logger.error("无法获取音频服务，跳过欢迎处理")
            return
            
        # 获取对应流量等级的话术文件名
        speech_file = self.flow_level_files.get(flow_level)
        if not speech_file:
            self.logger.error(f"未找到流量等级 {flow_level} 对应的话术文件")
            return
            
        # 获取话术文件路径
        speech_file_path = os.path.join(self.welcome_speech_dir, speech_file)
        if not os.path.exists(speech_file_path):
            self.logger.error(f"话术文件不存在: {speech_file_path}")
            return
            
        for username in users:
            try:
                # 从对应的话术文件中随机获取一行
                with open(speech_file_path, 'r', encoding='utf-8') as f:
                    speeches = [line.strip() for line in f.readlines() if line.strip()]
                    if not speeches:
                        self.logger.warning(f"话术文件为空: {speech_file}")
                        continue
                    
                    speech_text = random.choice(speeches)
                    
                    # 替换变量
                    speech_text = self._replace_variables(speech_text, username)
                    
                    # 创建音频项
                    audio_item = AudioItem(
                        id=str(uuid.uuid4()),
                        file_path="",
                        title=speech_text,
                        source_type="welcome",
                        metadata={
                            "original_type": "欢迎话术",
                            "is_temporary": True,  # 标记为临时话术
                            "file_name": speech_file,
                            "username": username,
                            "flow_level": flow_level
                        }
                    )
                    
                    # 添加到队列顶部，确保优先播放
                    audio_service.add_to_queue_front(audio_item)
                    
                    self.logger.info(f"已添加用户欢迎到播放队列顶部: {username}")
            except Exception as e:
                self.logger.error(f"处理用户欢迎失败: {str(e)}")
    
    def _load_welcome_speeches(self):
        """加载欢迎话术"""
        try:
            # 确保欢迎话术目录存在
            if not os.path.exists(self.welcome_speech_dir):
                os.makedirs(self.welcome_speech_dir, exist_ok=True)
                self.logger.info(f"创建欢迎话术目录: {self.welcome_speech_dir}")
            
            # 确保所有流量等级的话术文件存在
            for level, filename in self.flow_level_files.items():
                file_path = os.path.join(self.welcome_speech_dir, filename)
                if not os.path.exists(file_path):
                    # 只创建空文件
                    with open(file_path, "w", encoding="utf-8") as f:
                        pass
                    self.logger.info(f"创建{level}流量欢迎话术文件: {filename}")
            
            # 加载所有话术文件内容
            for level, filename in self.flow_level_files.items():
                file_path = os.path.join(self.welcome_speech_dir, filename)
                try:
                    with open(file_path, "r", encoding="utf-8") as f:
                        speeches = [line.strip() for line in f.readlines() if line.strip()]
                        if speeches:
                            self._speeches[level] = speeches
                            self.logger.info(f"已加载{level}流量欢迎话术文件: {filename}, {len(speeches)}条")
                        else:
                            self.logger.warning(f"{level}流量欢迎话术文件为空: {filename}")
                except Exception as e:
                    self.logger.error(f"加载欢迎话术文件失败: {filename}, {str(e)}")
            
            if not self._speeches:
                self.logger.warning("未找到任何有效的欢迎话术，请确保话术文件中包含有效内容")
                
        except Exception as e:
            self.logger.error(f"加载欢迎话术失败: {str(e)}")
            import traceback
            self.logger.error(traceback.format_exc())
    
    def _replace_variables(self, speech: str, username: str) -> str:
        """
        替换话术中的变量
        
        @param speech: 原始话术
        @param username: 用户名
        @return: 替换后的话术
        """
        # 处理用户名并替换
        processed_username = process_username(username)
        self.logger.debug(f"用户名处理: 原始='{username}', 处理后='{processed_username}'")
        speech = speech.replace("{用户名}", processed_username)
        
        # 替换时间
        now = datetime.now()
        speech = speech.replace("{时间}", now.strftime("%H:%M"))
        
        # 替换日期
        speech = speech.replace("{日期}", now.strftime("%Y-%m-%d"))
        
        return speech 